﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;

namespace T03ChatServer
{
    class HamdleClient
    {
        private Socket clientSocket;
        private string clientNo;
        private Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();

        public void StartClient(Socket clientSocket,string clientNo,
            Dictionary<string,Socket> clientList)
        {
            this.clientSocket = clientSocket;
            this.clientNo = clientNo;
            this.clientList = clientList;
            Thread t = new Thread(Chat);
            t.IsBackground = true;
            t.Start();
        }

        private void Chat()
        {
            byte[] bytesFromClient = new byte[4096];
            string dataFromClient;
            string msgTemp = null;
            byte[] bytesSend = new byte[4096];
            bool isListen = true;

            try
            {
                while (isListen)
                {
                    //处理客户端的信息
                    int len = clientSocket.Receive(bytesFromClient);
                    dataFromClient = Encoding.UTF8.GetString(bytesFromClient, 0, len);
                    if (!string.IsNullOrWhiteSpace(dataFromClient))
                    {
                        dataFromClient = dataFromClient.Substring(0, dataFromClient.LastIndexOf("$"));
                        if (!string.IsNullOrWhiteSpace(dataFromClient))
                        {
                            //有效信息发送给所有的客户端-即广播
                            Broadcast.PushMessage(dataFromClient, clientNo, clientList, Broadcast.CLIENT_MSG);
                            msgTemp = clientNo + ":" + dataFromClient + "\t\t" + DateTime.Now;
                            File.AppendAllText("E:\\MsgRecord.txt",msgTemp,Encoding.UTF8);

                        }
                        else
                        {
                            //客户端只发送一个“$”，表明主动关闭连接
                            //从字典中移除，当前用户
                            clientList.Remove(clientNo);
                            clientSocket.Close();
                            clientSocket = null;
                            isListen = false;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //从字典中移除，当前用户
                clientList.Remove(clientNo);
                clientSocket.Close();
                clientSocket = null;
                isListen = false;
                Debug.WriteLine(e.ToString());
            }
        }
    }
}
